package top.techqi.app.wol

import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.AllCaps
import android.text.InputFilter.LengthFilter
import android.text.TextWatcher
import android.view.View
import androidx.core.net.toUri
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.canhub.cropper.CropImageContract
import com.canhub.cropper.CropImageContractOptions
import com.canhub.cropper.CropImageOptions
import top.techqi.app.wol.databinding.FragmentEditBinding
import top.techqi.app.wol.utils.ImageUtils
import top.techqi.base.BaseFragment
import top.techqi.base.util.toast

class EditFragment : BaseFragment<FragmentEditBinding>(FragmentEditBinding::inflate) {
    private val mainViewModel by activityViewModels<MainViewModel>()
    private var imageUri: Uri? = null
    private var localImagePath: String? = null
    private var deviceId: Int? = null
    private var isEditMode = false

    private val cropImage = registerForActivityResult(CropImageContract()) { result ->
        if (result.isSuccessful) {
            imageUri = result.uriContent
            binding.imgIcon.setImageURI(imageUri)
            
            // 将裁剪后的图片保存到本地
            imageUri?.let { uri ->
                val savedPath = ImageUtils.saveImageToLocal(requireContext(), uri)
                if (savedPath != null) {
                    localImagePath = savedPath
                    toast("图片已保存到本地")
                } else {
                    toast("图片保存失败")
                }
            }
        }
    }
    private val pickImage = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) {
        cropImage.launch(CropImageContractOptions(it, CropImageOptions(fixAspectRatio = true)))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 检查是否为编辑模式
        deviceId = arguments?.getInt("deviceId")
        isEditMode = deviceId != null

        if (isEditMode) {
            // 编辑模式：加载现有设备数据
            deviceId?.let { id ->
                val device = mainViewModel.getDeviceById(id)
                device?.let {
                    binding.edtName.setText(it.name)
                    binding.edtAddr.setText(it.addr)
                    if (it.icon != null) {
                        // 优先从本地路径加载图片
                        localImagePath = it.icon
                        val bitmap = ImageUtils.loadImageFromLocal(it.icon)
                        if (bitmap != null) {
                            binding.imgIcon.setImageBitmap(bitmap)
                        } else {
                            // 如果本地图片不存在，尝试从Uri加载
                            imageUri = it.icon.toUri()
                            binding.imgIcon.setImageURI(imageUri)
                        }
                    }
                }
            }
        }

        // 限制输入字符为 0-9、A-F 和分隔符
        val macFilter = InputFilter { source, start, end, dest, dstart, dend ->
            val allowedChars = "0123456789ABCDEFabcdef:"
            for (i in start until end) {
                if (!allowedChars.contains(source[i].toString())) return@InputFilter ""
            }
            null // 允许合法输入
        }
        binding.edtAddr.filters = arrayOf(AllCaps(), LengthFilter(17), macFilter)
        binding.imbIcon.setOnClickListener {
            pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }
        binding.edtAddr.addTextChangedListener(object : TextWatcher {
            private var isFormatting = false
            private val separator = ':'
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                if (isFormatting) return

                isFormatting = true
                // 移除所有分隔符，保留纯字符
                val originalStr = s.toString().replace(separator.toString(), "")
                val formattedStr = StringBuilder()

                // 每两个字符插入分隔符
                for (i in originalStr.indices) {
                    formattedStr.append(originalStr[i].uppercaseChar())
                    if ((i + 1) % 2 == 0 && i != originalStr.lastIndex) {
                        formattedStr.append(separator)
                    }
                }

                // 更新文本并处理光标位置
                binding.edtAddr.setText(formattedStr.toString())
                binding.edtAddr.setSelection(binding.edtAddr.text?.length ?: 0)
                isFormatting = false
            }
        })


        binding.btnSave.setOnClickListener {
            val addr = binding.edtAddr.text.toString()
            if (addr.length != 17) {
                toast(R.string.main_edit_tips_addr_illegal)
                return@setOnClickListener
            }
            
            if (isEditMode && deviceId != null) {
                // 编辑模式：更新设备
                mainViewModel.updateDevice(
                    deviceId!!, localImagePath, binding.edtName.text.toString(), addr
                )
                toast("设备已更新")
            } else {
                // 新增模式：添加设备
                mainViewModel.appendDevice(
                    localImagePath, binding.edtName.text.toString(), addr
                )
                toast("设备已添加")
            }
            findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
        }
    }
}